<?php

/**
 * articulo actions.
 *
 * @package    catalogo
 * @subpackage articulo
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class articuloActions extends sfActions
{
	
	public function executeRepublicar(sfWebRequest $request)
	{
    $this->forward404Unless($this->articulo = Doctrine::getTable('Articulo')->findOneBy('token', 
      $request->getParameter('token'))); 
	}
	
  public function executeBuscar(sfWebRequest $request)
  {
    $this->forwardUnless($q = $request->getParameter('q'), 'articulo', 'destacados');

    //$this->articulos = Doctrine_Core::getTable('Articulo')->getForLuceneQuery($q);
    $this->articulos = Doctrine_Core::getTable('Articulo')->searchByIndex($q);
    $this->q = $q;

	  if ($request->isXmlHttpRequest())
	  {
		  if ('*' == $q || !$this->articulos)
	    {
	      return $this->renderText('No hay resultados.');
	    }	  	
	    return $this->renderPartial('articulo/ajax_list', array('articulos' => $this->articulos, 'q'=>$q));
	  }    
  }
	
  public function executeDestacados(sfWebRequest $request)
  {
		$q = Doctrine_Query::create()
	    ->from('Articulo a')
		  ->where('a.destacado=1 AND a.publicado=1')
	    ->limit(12)
		  ->orderBy('RAND()');
		$this->articulos = $q->execute();
  }

  public function executeShow(sfWebRequest $request)
  {
    $this->articulo = $articulo = Doctrine::getTable('Articulo')->find(array($request->getParameter('id')));
    $this->forward404Unless($this->articulo);
    
    $consulta = new ConsultaArticulo();
    $consulta->setArticuloId($articulo->getId());
    $this->cform = new ConsultaArticuloForm($consulta);

    if ($articulo->getPublicado()===1) //si está publicado, incremento el contador de visitas en 1
    {
      $articulo->setVisitas($articulo->getVisitas() + 1);
      $articulo->save();
    }
  }

  public function executeNew(sfWebRequest $request)
  {
		$art = new Articulo();
		$art->setPublicado(0);  
		$this->form = new ArticuloForm($art);	
  }

  public function executeCreate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST));

    $this->form = new ArticuloForm();

    $this->processForm($request, $this->form);

    $this->setTemplate('new');
  }

  public function executeEdit(sfWebRequest $request)
  {
    $this->forward404Unless($articulo = Doctrine::getTable('Articulo')->find(array($request->getParameter('id'))), sprintf('Object articulo does not exist (%s).', $request->getParameter('id')));
    $this->form = new ArticuloForm($articulo);
  }

  public function executeUpdate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST) || $request->isMethod(sfRequest::PUT));
    $this->forward404Unless($articulo = Doctrine::getTable('Articulo')->find(array($request->getParameter('id'))), sprintf('Object articulo does not exist (%s).', $request->getParameter('id')));
    $this->form = new ArticuloForm($articulo);

    $this->processForm($request, $this->form);

    $this->setTemplate('edit');
  }

  public function executeDelete(sfWebRequest $request)
  {
    $request->checkCSRFProtection();

    $this->forward404Unless($articulo = Doctrine::getTable('Articulo')->find(array($request->getParameter('id'))), sprintf('Object articulo does not exist (%s).', $request->getParameter('id')));
    $articulo->delete();

    $this->redirect('@homepage');
  }

  protected function processForm(sfWebRequest $request, sfForm $form)
  {
    $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));    
    if ($form->isValid())
    {
      $articulo = $form->save();

      $this->getUser()->setFlash('notice', 'El anuncio se ha modificado correctamente.');
      
      $this->getController()->genUrl(array('sf_route' => 'editar_articulo', 'sf_subject' => $articulo), false);
    }
  }
  
  public function executeNewContacto(sfWebRequest $request)
  {
    $c_art = new ContactoArticulo();
    $c_art->setArticuloId($request->getParameter('id'));
    $this->form = new ContactoArticuloForm($c_art); 
  }
  
  public function executeCreateContacto(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod(sfRequest::POST));

    $this->form = new ContactoArticuloForm();

    $this->processFormContacto($request, $this->form);

    $this->setTemplate('newContacto');
  }
  
  protected function processFormContacto(sfWebRequest $request, sfForm $form)
  {
    $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));    
    if ($form->isValid())
    {
      $c_articulo = $form->save();
      $this->notificarVendedorInteresado($c_articulo);
      
      $this->getUser()->setFlash('notice', 'El mensaje se ha enviado correctamente.');
      
      $this->redirect('articulo/newContacto'. '?id=' . $request->getParameter('aid'));
    }
  }
  
  protected function notificarVendedorInteresado($contacto)
  {

    $articulo = $contacto->getArticulo();
    $vendedor = $articulo->getUsuario();
    $email = $vendedor->getEmail();
    
    $nombre_interesado = $contacto->getNombre();
    $email_interesado  = $contacto->getEmail();
    $texto_interesado  = $contacto->getTexto();
        
    $username = substr($email, 0, strpos($email, '@'));
  
    $enlace_pqn = '<a href="' . $_SERVER["SERVER_NAME"] . '">PorQueNuevo</a>';    
    
    // send an email to the user
    $body = <<<EOF
Hola {$username},

Un interesado en tu artículo te ha enviado un mensaje.
Estos son los detalles del mensaje:

---------------------------------------------------
De: {$nombre_interesado} / {$email_interesado} 

{$texto_interesado}

---------------------------------------------------

Muchas gracias por elegirnos.
El equipo de {$enlace_pqn}.
EOF;

    $message = $this->getMailer()->compose();
    $message->setSubject('PorQueNuevo: Hay un interesado en tu artículo');
    $message->setTo($email);
    $message->setFrom(array('info@porquenuevo.com.ar' => 'PorQueNuevo'));
    $message->setReplyTo($email_interesado);
    $message->setBody(nl2br($body), 'text/html');
 
    $this->getMailer()->send($message);
  }  
}
